<?php

namespace dengje\workerman\process\websocket;

use dengje\workerman\process\timing\task\Test;
use Workerman\Worker;
use Workerman\Timer;
use Workerman\Connection\TcpConnection;

class Handler
{
    public $worker;
    public function onWorkerStart(Worker $worker): void
    {

        $this->worker = $worker;
    }

    public function onConnect($connection)
    {
        $worker = $this->worker;
        $connection->send('连接成功' . $connection->id);
        Timer::add(2, function () use ($worker) {
            // 遍历当前进程所有的客户端连接，发送当前服务器的时间
            $has = count($worker->connections);
            foreach ($worker->connections as $connection) {
                $connection->send('在线人数:'.$has);
            }
        });
        // 设置连接的onMessage回调
        $connection->onMessage = function (TcpConnection $connection, $data) {
            var_dump($data);
            // $load = sys_getloadavg();

            // $data = $load[0];
            // // 每2.5秒执行一次
            // $time_interval = 1;
            // Timer::add($time_interval, function () use($connection,$data){
            //     $connection->send('receive success' . $data);
            // });
            $connection->send('receive success' . $data);
        };

        // 设置连接的onClose回调
        $connection->onClose = function (TcpConnection $connection) {
            $this->worker->connections[$connection->id];
        };
    }
}